package com.caiyi.financial.nirvana.sms.service;

import com.caiyi.financial.nirvana.sms.base.service.BaseService;
import com.caiyi.financial.nirvana.sms.entity.SmsMsg;
import com.caiyi.financial.nirvana.sms.enums.ReturnCodeEnum;
import com.caiyi.financial.nirvana.sms.mapper.SmsMsgMapper;
import com.caiyi.financial.nirvana.sms.querybean.*;
import com.caiyi.financial.nirvana.sms.queue.SendQueueEntity;
import com.caiyi.financial.nirvana.sms.util.DateUtil;
import com.caiyi.financial.nirvana.sms.vo.SmsAccountVo;
import com.caiyi.financial.nirvana.sms.vo.SmsPriceVo;
import com.caiyi.financial.nirvana.sms.vo.SmsRateVo;
import com.github.pagehelper.PageHelper;
import com.youyu.common.utils.YyAssert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

@Service
public class SmsMsgService extends BaseService<SmsMsg> {

    @Autowired
    private SmsMsgMapper smsMsgMapper;
    @Value("${caiyi.company.accounts}")
    private String caiyiAccounts;

    @Value("${finance.company.accounts}")
    private String financeAccounts;


    public List<String> getSmsByProvince() {
        return smsMsgMapper.getSmsByProvince();
    }

    /**
     * 根据phone更新数据省市
     */
    public int setProvinceAndCityByPhone(String province, String city, String phone) {
        return smsMsgMapper.updateProvinceAndCityByPhone(province, city, phone);
    }

    /**
     * 查询一个月内的移动发送条数
     *
     * @return 条数
     */
    public int getCountAndGetWayId(int gateWayId) {
        return smsMsgMapper.getCountByGetWayId(gateWayId);
    }

    /**
     * 定时查询短信发送的成功率
     *
     * @return 成功率
     */
    public List<SmsRateVo> getMsgSuccessRate() {
        return smsMsgMapper.selectMsgSuccessRate();
    }

    /**
     * 定时查询短信发送的失败率
     *
     * @return 成功率
     */
    public List<SmsRateVo> getMsgFailedRate() {
        return smsMsgMapper.selectMsgFailedRate();
    }


    public PageBean<SmsMsg> getMsgByParams(QueryMsgBean bean) {
        YyAssert.isFalse(null == bean.getStartTime(), ReturnCodeEnum.PARAMS_ERROR.code, "开始时间不能为空");
        if (null == bean.getEndTime()) {
            bean.setEndTime(new Date());
        }
        YyAssert.isFalse(DateUtil.getDateDiffer(bean.getStartTime(), bean.getEndTime()) > 7, ReturnCodeEnum.PARAMS_ERROR.code, "开始时间和结束时间不能大于7天");
        PageHelper.startPage(bean.getPageNum(), bean.getPageSize());
        List<SmsMsg> list = smsMsgMapper.selectMsgListByParams(bean);
        PageBean<SmsMsg> pageBean = new PageBean<>(list);
        return pageBean;
    }

    public List<SendQueueEntity> handleUnknownStatus() {
        try {
            return smsMsgMapper.selectMsgByStatus();
        } catch (Exception e) {
            logger.error("handleUnknownStatus error....", e);
        }
        return null;
    }

    public PageBean<SmsAccountVo> getMsgByDayByAccount(MsgDayQueryBean bean) {
        PageHelper.startPage(bean.getPageNum(), bean.getPageSize());
        List<SmsAccountVo> list = smsMsgMapper.selectMsgByDayByAccount(bean);
        PageBean<SmsAccountVo> pageBean = new PageBean<>(list);
        return pageBean;
    }

    public PageBean<SmsAccountVo> getMsgByMonthByAccount(MsgMonthQueryBean bean) {
        PageHelper.startPage(bean.getPageNum(), bean.getPageSize());
        List<SmsAccountVo> list = smsMsgMapper.selectMsgByMonthByAccount(bean);
        PageBean<SmsAccountVo> pageBean = new PageBean<>(list);
        return pageBean;
    }

    public PageBean<SmsAccountVo> getMsgByDayByGateway(GatewayDayQueryBean bean) {
        PageHelper.startPage(bean.getPageNum(), bean.getPageSize());
        List<SmsAccountVo> list = smsMsgMapper.selectMsgByDayByGateway(bean);
        PageBean<SmsAccountVo> pageBean = new PageBean<>(list);
        return pageBean;
    }

    public PageBean<SmsAccountVo> getMsgByMonthByGateway(GatewayMonthQueryBean bean) {
        PageHelper.startPage(bean.getPageNum(), bean.getPageSize());
        List<SmsAccountVo> list = smsMsgMapper.selectMsgByMonthByGateway(bean);
        PageBean<SmsAccountVo> pageBean = new PageBean<>(list);
        return pageBean;
    }

    public PageBean<SmsAccountVo> getMsgByDayBySystem(MsgDayQueryBean bean) {
        PageHelper.startPage(bean.getPageNum(), bean.getPageSize());
        List<SmsAccountVo> list = smsMsgMapper.selectMsgByDayBySystem(bean);
        PageBean<SmsAccountVo> pageBean = new PageBean<>(list);
        return pageBean;
    }

    public PageBean<SmsAccountVo> getMsgByMonthBySystem(MsgMonthQueryBean bean) {
        PageHelper.startPage(bean.getPageNum(), bean.getPageSize());
        List<SmsAccountVo> list = smsMsgMapper.selectMsgByMonthBySystem(bean);
        PageBean<SmsAccountVo> pageBean = new PageBean<>(list);
        return pageBean;
    }

    public Map getMsgByMonthBySystemBill(String month, String caiyiAccounts, String financeAccounts) {
        Map data = new HashMap();

        //彩亿公司主体下属账号
        List<String> caiyiAccountList = Arrays.asList(caiyiAccounts.split(","));
        //彩亿互金主体下属账号
        List<String> financeAccountList = Arrays.asList(financeAccounts.split(","));
        StringBuffer account = new StringBuffer();
        for (String s : caiyiAccountList) {
            account.append(",'" + s + "'");
        }
        for (String s : financeAccountList) {
            account.append(",'" + s + "'");
        }
        String accountParam = account.toString().replaceFirst(",", "");
        List<SmsPriceVo> list = smsMsgMapper.getMonthGateway(month, accountParam);
        List<SmsPriceVo> monthBillList = smsMsgMapper.getMsgMonthExcel(month);

        Map caiyiMap = new HashMap();
        Map financeMap = new HashMap();
        Map otherMap = new HashMap();
        for (SmsPriceVo smsPriceVo : monthBillList) {
            if (caiyiAccountList.contains(smsPriceVo.getAccount())) {
                dataSpec(caiyiMap, smsPriceVo);
                continue;
            }
            if (financeAccountList.contains(smsPriceVo.getAccount())) {
                dataSpec(financeMap, smsPriceVo);
                continue;
            }
            dataSpec(otherMap, smsPriceVo);
        }
        data.put("list", list);
        data.put("caiyiMap", caiyiMap);
        data.put("financeMap", financeMap);
        data.put("otherMap", otherMap);
        return data;
    }

    private void dataSpec(Map map, SmsPriceVo smsPriceVo) {
        List accountList = (List) map.get(smsPriceVo.getAccount() + ":" + smsPriceVo.getName());
        if (null == accountList || accountList.size() == 0) {
            List<SmsPriceVo> tempList = new ArrayList<>();
            tempList.add(smsPriceVo);
            map.put(smsPriceVo.getAccount() + ":" + smsPriceVo.getName(), tempList);
        } else {
            accountList.add(smsPriceVo);
        }
    }


    /**
     * 重新生成三天之前的统计数据
     */
    public void threeDaysAgo() {
        try {
            int count = 0;
            Map<String, String> param = new HashMap();
            List<Map> listMapDay = smsMsgMapper.searchThreeDaysAgoSmsDayAccount();
            for (Map<String, Object> map : listMapDay) {
                param.put("gatewayId", map.get("gatewayId") + "");
                param.put("msgCount", map.get("msgCount") + "");
                param.put("successCount", map.get("successCount") + "");
                param.put("unknownCount", map.get("unknownCount") + "");
                param.put("failureCount", map.get("failureCount") + "");
                param.put("day", map.get("day") + "");
                param.put("account", map.get("account") + "");
                logger.info("threeDaysAgo param : {}", param);
                int num = smsMsgMapper.threeDaysAgoSmsDayAccount(param);
                if (num == 0) {
                    smsMsgMapper.insertSmsDayAccountUser(param);
                }
                count = num > 0 ? ++count : count;
            }
            logger.info("threeDaysAgoSmsDayAccount update rows {}", count);
        } catch (Exception e) {
            logger.error("threeDaysAgo error ", e);
        }
    }


    /**
     * 客户日发送统计缓存表sms_day_account
     */
    public void smsDayAccount() {
        try {
            List<SmsAccountVo> listMap = smsMsgMapper.searchSmsDayAccount();
            int count = 0;
            Map<String, String> param = new HashMap();
            for (SmsAccountVo smsAccountVo : listMap) {
                param.put("gatewayId", smsAccountVo.getGatewayId() + "");
                param.put("msgCount", smsAccountVo.getMsgCount() + "");
                param.put("successCount", smsAccountVo.getSuccessCount() + "");
                param.put("unknownCount", smsAccountVo.getUnknownCount() + "");
                param.put("failureCount", smsAccountVo.getFailureCount() + "");
                param.put("day", smsAccountVo.getDay());
                param.put("account", smsAccountVo.getAccount());
                param.put("price", smsAccountVo.getPrice() + "");
                logger.info("smsDayAccount SmsDayAccount param : {}", param);
                int num = smsMsgMapper.updateSmsDayAccount(param);
                if (num == 0) {
                    smsMsgMapper.insertSmsDayAccountUser(param);
                }
                count = num > 0 ? ++count : count;
            }
            logger.info("客户日发送统计更新结果 : {}", count);
        } catch (Exception e) {
            logger.error("smsDayAccount error....", e);
        }
    }

    public Map getDayBillDetail(String date, String account) {
        Map data = new HashMap();
        List<SmsPriceVo> list = smsMsgMapper.getDayBillDetail(date, account);
        BigDecimal decimal = new BigDecimal(0);
        for (SmsPriceVo smsPriceVo : list) {
            decimal = decimal.add(smsPriceVo.getTotalPrice());
        }
        data.put("list", list);
        data.put("sumPrice", decimal.toString());
        return data;
    }


    public Map getMonthBillDetail(String date, String account) {
        Map data = new HashMap();
        List<SmsPriceVo> list = smsMsgMapper.getMonthBillDetail(date, account);
        BigDecimal decimal = new BigDecimal(0);
        for (SmsPriceVo smsPriceVo : list) {
            decimal = decimal.add(smsPriceVo.getTotalPrice());
        }
        data.put("list", list);
        data.put("sumPrice", decimal.toString());
        return data;
    }

    /**
     * 修改统计表统计数据（修复）
     */
    public void testUpdateMsgCount(int start, int end) {
        int count = 0;
        try {
            List<Map> listMapDay = smsMsgMapper.searchThreeDayDetail(start, end);
            logger.info("listMapDay size {}", listMapDay.size());
            Map<String, String> param = new HashMap();
            for (Map<String, Object> map : listMapDay) {
                param.put("gatewayId", map.get("gatewayId") + "");
                param.put("msgCount", map.get("msgCount") + "");
                param.put("successCount", map.get("successCount") + "");
                param.put("unknownCount", map.get("unknownCount") + "");
                param.put("failureCount", map.get("failureCount") + "");
                param.put("day", map.get("day") + "");
                param.put("account", map.get("account") + "");
                param.put("price", map.get("price") + "");
                logger.info("testUpdateMsgCount param : {}", param);
                //int detNum = smsMsgMapper.deleteSmsDayAsccount(param);
                //logger.info("testUpdateMsgCount delete deleteNum :{} , param :{}", detNum, param);
                int num = smsMsgMapper.updateThreeDayDetail(param);
                if (num == 0) {
                    smsMsgMapper.insertSmsDayAccountUser(param);
                }
                count = num > 0 ? ++count : count;
            }
            logger.info("testUpdateMsgCount update rows {}", count);
        } catch (Exception e) {
            logger.error("testUpdateMsgCount error ", e);
        }
    }

    public long countSmsMsg() {
        long count = 0L;
        try {
            count = smsMsgMapper.countSmsMsg();
        } catch (Exception e) {
            logger.error("countSmsMsg error ", e);
        }
        return count;
    }
}
